<template>
  <button
    :class="comClazz"
    :style="comStyle"
    :disabled="disabled"
    @click="handleClick"
  >
    <span v-if="$slots.default"><slot></slot></span>
  </button>
</template>

<script lang="ts">
import { computed, defineComponent, PropType } from "vue";

export type ButtonType =
  | "primary"
  | "secondary"
  | "success"
  | "warning"
  | "error"
  | "danger"
  | "info"
  | "default"
  | "text"
  | "link";

export default defineComponent({
  name: "MButton",
  props: {
    type: {
      type: String as PropType<ButtonType>,
      default: "default",
      validator: (val: string) => {
        return [
          "default",
          "primary",
          "secondary",
          "success",
          "warning",
          "text",
          "link",
          "danger",
          "info",
        ].includes(val);
      },
    },
    size: {
      type: String,
      default: "medium",
    },
    icon: {
      type: String,
      default: "",
    },
    loading: Boolean,
    disabled: Boolean,
    round: Boolean,
    block: Boolean,
    ghost: Boolean,
    // hotfil的渐变背景按钮
    gradient: {
      type: [Boolean, String],
      default: false,
    },
  },
  emits: ["click"],
  setup(props, { emit }) {
    const comClazz = computed(() =>
      [
        "m-button",
        `m-button--${props.type}`,
        props.size ? `m-button--${props.size}` : "",
        {
          "is-disabled": props.disabled, // 状态全部以 is-开头
          "is-loading": props.loading,
          "is-round": props.round,
          "is-ghost": props.ghost,
          "is-block": props.block,
          "is-gradient": props.gradient,
        },
      ].filter(Boolean)
    );
    const comStyle = computed(() => {
      const style: Record<string, any> = {};
      if (props.gradient) {
        if (typeof props.gradient === "boolean") {
          style.background =
            "linear-gradient(to right, #fbe167, #f0b03d, #ec9b37)";
        } else {
          style.background = props.gradient;
        }
      }
      return style;
    });
    const handleClick = (e) => {
      if (props.loading || props.disabled) {
        return false;
      }
      emit("click", e);
    };
    return {
      comClazz,
      comStyle,
      handleClick,
    };
  },
});
</script>
